﻿using System;
using System.Collections.Generic;
using System.Net;

namespace Com.ZGH.Dns
{
    public class DnsAnswer : IElement
    {
        private DnsName query;
        private short queryType;
        private short queryClass;
        private int ttl;
        private short resLength;
        private byte[] resData;

        public DnsName Query
        {
            get { return query; }
            set { query = value; }
        }

        public short QueryType
        {
            get { return queryType; }
            set { queryType = value; }
        }

        public short QueryClass
        {
            get { return queryClass; }
            set { queryClass = value; }
        }

        public int Ttl
        {
            get { return ttl; }
            set { ttl = value; }
        }

        public short ResLength
        {
            get { return resLength; }
            set { resLength = value; }
        }

        public byte[] ResData
        {
            get { return resData; }
            set { resData = value; }
        }

        public int Size
        {
            get {return query.Size + 10 + resLength; }
        }

        public byte[] ToBytes()
        {
            var bytes = new List<byte>();

            bytes.AddRange(query.ToBytes());

            bytes.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(queryType)));

            bytes.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(queryClass)));

            bytes.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(ttl)));

            bytes.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(resLength)));

            bytes.AddRange(resData);

            return bytes.ToArray();
        }

        public static DnsAnswer Parse(byte[] value, int start)
        {
            var answer = new DnsAnswer();

            answer.query = DnsName.Parse(value, start);

            answer.queryType = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(value, start + answer.query.Size));

            answer.queryClass = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(value, start + answer.query.Size + 2));

            answer.ttl = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(value, start + answer.query.Size + 4));

            answer.resLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(value, start + answer.query.Size + 8));

            answer.resData = new byte[answer.resLength];

            Array.Copy(value, start + answer.query.Size + 10, answer.resData, 0, answer.resLength);

            return answer;
        }
    }
}
